package test.org.nanotek.jpa;

/**
 * Helper class to test  Domain Model, on Hibernate Entity Manager.
 * 
 * @author josecanovamauger.
 * 
 */
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.nanotek.Base;
import org.nanotek.persistence.DAOException;
import org.nanotek.persistence.jpa.BrainzBaseDAO;

public class EntityManagerStart {

	protected EntityManagerFactory emf;
	protected EntityManager entityManager;
	
	@Before
	public void start()
	{ 
		emf = Persistence.createEntityManagerFactory("musicbrainz");
		entityManager = emf.createEntityManager();
	}
	
	@Test
	public  void test(){ 
		System.out.println("lights on");
	};
	
	@After
	public void shutDown()
	{ 
		if (entityManager !=null && entityManager.isOpen()) 
			entityManager.close();
		if (emf !=null && emf.isOpen()) 
			emf.close();
	}
	
	public <T extends Base<?>> BrainzBaseDAO<T>  getDAO(Class<T> clazz)
	{ 
		
		BrainzBaseDAO<T> bbd = new DaoBuilder<T>().set(clazz).setEntityManager(entityManager).build();
		return bbd;
	}
	

	public <T extends BrainzBaseDAO<?>> T  configure(final T  dao)
	{ 
		return new EntityManagerConfigurator().configure(dao, entityManager);
	}
	
	public void countRecords (BrainzBaseDAO<?> ... daos)
	{ 
		for (BrainzBaseDAO<?> d:daos)
		{ 
			if (d.countRecords() <=0)
				throw new DAOException ("Error persisting");
			
		}
		
	}
	
	class DaoBuilder <T extends Base<?>>{ 
		
		BrainzBaseDAO<T> bbd = new BrainzBaseDAO<T>();
		
		public DaoBuilder() {
			
		}
		
		public DaoBuilder<T> set(Class<T> clazz)
		{ 
			bbd.setBaseClass(clazz);
			return this;
		}
		
		public DaoBuilder<T> setEntityManager(EntityManager emf)
		{ 
			bbd.setEntityManager(emf);
			return this;
		}
		
		public BrainzBaseDAO<T> build()
		{ 
			return bbd;
		}
	}
	
	class EntityManagerConfigurator { 
		<T extends BrainzBaseDAO<?>> T  configure(final T  dao, EntityManager emf)
			{ 
				dao.setEntityManager(emf);
				if (dao.getBaseClass() == null) 
				{ 
					throw new DAOException("Invalid DAO Subclass");
				}
				return dao;
		}
	}
      
}
